package com.example.anni.zhuzhoujia.bogege;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemClickListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by 张钧博 on 2016/6/10.
 */
public class SeeNewsActivity extends AppCompatActivity implements OnMenuItemClickListener {
    private WebView newsWebview;
    private ProgressDialog mProgressDialog;
    private ImageButton ivSeeNewsBack;
    private PopupWindow menuPopupWindow;
    private TextView tvNewsNumber, tvGood, tvBad;
    private TextView tvCommentnumButtom;
    private TextView tvNewsTitle;
    private TextView tvNewsResource, tvSendComment;
    private TextView tvNewsTime, seeMoreComment, tvRelated, tvCommentNone;
    private LinearLayout llKeyboard, goodLinnear, badLinear;

    private String newsTitle, newsCover, newsSunmmary, fromUrl;

    private ImageView newsCommentAvatar;
    private TextView newsCommentNickname;
    private ImageView newsCommentSex, ivShare;
    private ImageView good;
    private TextView newsCommentGoodNumber;
    private ImageView bad;
    private TextView newsCommentBadNumber;
    private TextView newsCommentTime;
    private TextView newsCommentContent;
    private TextView newsCommentArea;
    private RelativeLayout rvMoreComment;
    private Toolbar seeNewsToolbar;
    private EditText sendMyComment;

    private int width;
    private int height;
    private int actionBarHeight;

    private String evText;
    private String newsId;
    private int bool;

    private List<Map<String, String>> commentList = new ArrayList<Map<String, String>>();
    private List<Map<String, String>> relatedList = new ArrayList<Map<String, String>>();

    private ListView lvNewsComments, seeNewsRelated;
    private FragmentManager fragmentManager;
    private ContextMenuDialogFragment mMenuDialogFragment;

    /**
     * 返回按钮的监听
     */
    View.OnClickListener seeNewsBack = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //这行代码会结束ShareSDK的统计功能并释放资源
        ShareSDK.stopSDK(this);
    }

    /**
     * 创建菜单
     */
    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.see_news_menu, menu);
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.see_news);
        //初始化，如果不在所有的ShareSDK的操作之前调用这行代码，就会抛出空指针异常
        ShareSDK.initSDK(this);

        login();


        RequestParams aaa = new RequestParams("http://tr.zzapi.gson.cn/api/user/isLogin");
        x.http().get(aaa, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                JSONObject jsonObject = JSON.parseObject(s);
                String message = jsonObject.getString("message");
                //Toast.makeText(SeeNewsActivity.this, message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });

        newsId = getIntent().getStringExtra("newsId");

        x.view().inject(this);

        newsTitle = getIntent().getStringExtra("newsTitle");
        newsSunmmary = getIntent().getStringExtra("newsSunmmary");
        newsCover = getIntent().getStringExtra("newsCover");
        fromUrl = getIntent().getStringExtra("fromUrl");

        newsWebview = (WebView) findViewById(R.id.news_webview);
        tvNewsNumber = (TextView) findViewById(R.id.see_news_comment_number);
        tvCommentnumButtom = (TextView) findViewById(R.id.tv_commentnum_buttom);
        tvNewsTitle = (TextView) findViewById(R.id.tv_news_title);
        tvNewsResource = (TextView) findViewById(R.id.tv_news_resource);
        tvNewsTime = (TextView) findViewById(R.id.tv_news_time);
        lvNewsComments = (ListView) findViewById(R.id.lv_news_comment);
        rvMoreComment = (RelativeLayout) findViewById(R.id.rv_more_comment);
        seeMoreComment = (TextView) findViewById(R.id.see_news_comment_more);
        seeNewsRelated = (ListView) findViewById(R.id.see_news_related);
        tvRelated = (TextView) findViewById(R.id.tv_related);
        tvCommentNone = (TextView) findViewById(R.id.tv_comment_none);
        seeNewsToolbar = (Toolbar) findViewById(R.id.tl_custom);
        sendMyComment = (EditText) findViewById(R.id.sendmycomment);
        tvSendComment = (TextView) findViewById(R.id.tv_send_comment);
        ivShare = (ImageView) findViewById(R.id.iv_share);
        llKeyboard = (LinearLayout) findViewById(R.id.ll_keyboard);
        tvGood = (TextView) findViewById(R.id.good);
        tvBad = (TextView) findViewById(R.id.bad);
        goodLinnear = (LinearLayout) findViewById(R.id.good_linear);
        badLinear = (LinearLayout) findViewById(R.id.bad_linear);

        ivShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        sendMyComment.setOnClickListener(new SendMyCommentOnClickListener());
        tvSendComment.setOnClickListener(new SendCommentListener());
        good(newsId);
        bad(newsId);

        //设置自定义toolbar为ActionBar
        setSupportActionBar(seeNewsToolbar);


        fragmentManager = getSupportFragmentManager();
        initMenuFragment();

        readDate();
        WebSettings websettings = newsWebview.getSettings();
        websettings.setJavaScriptEnabled(true);
        websettings.setSupportZoom(true);
        websettings.setTextZoom(100);

        newsWebview.setWebViewClient(new MyWebViewClient());
        ivSeeNewsBack = (ImageButton) findViewById(R.id.see_news_back);
        ivSeeNewsBack.setOnClickListener(seeNewsBack);

        //获取屏幕的宽
        DisplayMetrics dm = getResources().getDisplayMetrics();
        width = dm.widthPixels;
        height = dm.heightPixels;

        //ActionBar的高度
        /*actionBarHeight = getSupportActionBar().getHeight();*/
        /*TypedValue tv = new TypedValue();
        if (this.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, this.getResources().getDisplayMetrics());
        }*/
    }

    private void login() {
        RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/user/login");
        params.addBodyParameter("userName", "博哥哥");
        params.addBodyParameter("password", "aaaaaa");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                //Toast.makeText(SeeNewsActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 读取数据
     */
    private void readDate() {
        RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/news/detail?id=" + newsId + "");
        params.addBodyParameter("userName", "博哥哥");
        params.addBodyParameter("password", "aaaaaa");
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String s) {
                JSONObject jsonobject = JSON.parseObject(s);
                JSONObject data = JSON.parseObject(jsonobject.getString("data"));
                JSONObject news = JSON.parseObject(data.getString("news"));

                String content = news.getString("content");
                String commentNum = news.getInteger("commentNum") + "";
                String newsTitle = news.getString("title");
                String newsSource = news.getString("source");
                String newsTime = news.getString("dateline");
                String newsGood = news.getString("good");
                String newsBad = news.getString("bad");
                tvGood.setText(newsGood);
                tvBad.setText(newsBad);


                final JSONArray comments = data.getJSONArray("comments");
                newsWebview.loadDataWithBaseURL("http://tr.zzapi.gson.cn/",
                        "<html>      <script type=\"text/javascript\">           function doResize(){                              var imgs = document.getElementsByTagName(\"img\");                for(var i = 0; i < imgs.length; i ++){                                        imgs[i].style.width = \"100%\";                              }                                  var ps = document.getElementsByTagName(\"p\");                for(var i = 0; i < ps.length; i ++){                     ps[i].style.lineHeight = \"150%\";                }           }      </script>      <body onload=\"doResize();\">" + content + "</body> </head>",
                        "text/html", "utf-8", null);
                tvNewsNumber.setText(commentNum + "跟帖");
                tvCommentnumButtom.setText(commentNum);
                tvNewsTitle.setText(newsTitle);
                tvNewsResource.setText(newsSource);
                tvNewsTime.setText(newsTime);

                for (int j = 0; j < comments.size(); j++) {

                    Map<String, String> commentMap = new HashMap<String, String>();
                    JSONObject comment = comments.getJSONObject(j);

                    String commentContent = comment.getString("content");
                    String commentDateline = (String) comment.get("dateline");

                    JSONObject commentUser = JSON.parseObject(comment.getString("user"));
                    if (commentUser != null) {
                        String area = commentUser.getString("area");
                        String avatar = commentUser.getString("avatar");
                        String commentNickName = commentUser.getString("nickName");
                        String commentGenter = commentUser.getString("gender");
                        //Toast.makeText(SeeNewsActivity.this,area , Toast.LENGTH_SHORT).show();

                        commentMap.put("area", area);
                        commentMap.put("avatar", avatar);
                        commentMap.put("commentNickName", commentNickName);
                        commentMap.put("commentGenter", commentGenter);
                    } else if (commentUser == null) {
                        commentMap.put("area", null);
                        commentMap.put("avatar", null);
                        commentMap.put("commentNickName", null);
                        commentMap.put("commentGenter", "");
                    }
                    commentMap.put("commentContent", commentContent);
                    commentMap.put("commentDateline", commentDateline);
                    commentList.add(commentMap);
                }

                /**
                 * 相关新闻的数据
                 */
                JSONArray relateds = data.getJSONArray("related");
                if (relateds != null) {
                    for (int i = 0; i < relateds.size(); i++) {
                        Map<String, String> relatedMap = new HashMap<String, String>();
                        JSONObject related = relateds.getJSONObject(i);

                        String newsTitle2 = related.getString("title");
                        String newsCommentNum2 = related.getString("commentNum");
                        if (related.getString("cover") != null) {
                            String newsCover2 = related.getString("cover");
                            relatedMap.put("newsCover2", newsCover2);
                        } else {
                            relatedMap.put("newsCover2", "");
                        }
                        String newsId = related.getInteger("id") + "";
                        String newsSource2 = related.getString("source");

                        relatedMap.put("newsTitle2", newsTitle2);
                        relatedMap.put("newsCommentNum2", newsCommentNum2);

                        relatedMap.put("newsId", newsId);
                        relatedList.add(relatedMap);
                    }
                }

                /**
                 * 添加新闻评论列表适配器
                 */
                lvNewsComments.setAdapter(new NewsCommentAdapter(comments));
                setTotalHeightofListView(lvNewsComments);
                if (tvCommentNone.getVisibility() == View.VISIBLE) {
                    seeMoreComment.setVisibility(View.GONE);
                } else {
                    seeMoreComment.setVisibility(View.VISIBLE);
                }

                //动态的设置为前三项item的高度
                /*BaseAdapter setHeightAdapter = (BaseAdapter) lvNewsComments.getAdapter();
                int threeHeight = 0;
                if (setHeightAdapter == null) {
                    return;
                }
                for (int j = 0; j < 3; j++) {
                    for (int i = 0, len = setHeightAdapter.getCount(); i < len; i++) {
                        threeHeight += 46;
                    }
                }
                ViewGroup.LayoutParams params = lvNewsComments.getLayoutParams();
                params.height = threeHeight + (lvNewsComments.getDividerHeight() * (setHeightAdapter.getCount() - 1));
                //listView.getDividerHeight()获取子项间分隔符占用的高度
                //params.height最后得到整个ListView完整显示需要的高度
                lvNewsComments.setLayoutParams(params);*/

                //查看全部评论
                rvMoreComment.setOnClickListener(new SeeMoreComment(newsId));
                tvNewsNumber.setOnClickListener(new SeeMoreComment(newsId));
                seeMoreComment.setOnClickListener(new SeeMoreComment(newsId));

                /**
                 * 相关新闻适配器
                 */
                class SeeNewsRelatedAdapter extends BaseAdapter {

                    @Override
                    public int getCount() {
                        return relatedList.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return relatedList.get(position);
                    }

                    @Override
                    public long getItemId(int position) {
                        return 0;
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {

                        if (relatedList != null) {
                            tvRelated.setVisibility(View.INVISIBLE);
                            View root = getLayoutInflater().inflate(R.layout.list_item, null);

                            ImageView newsCover2 = (ImageView) root.findViewById(R.id.news_cover);
                            TextView newsTitle2 = (TextView) root.findViewById(R.id.news_title);
                            TextView tvSummary2 = (TextView) root.findViewById(R.id.tv_sunmmary);
                            TextView tvCommentnum2 = (TextView) root.findViewById(R.id.tv_commentnum);


                            newsTitle2.setText((String) relatedList.get(position).get("newsTitle2"));
                            tvSummary2.setText((String) relatedList.get(position).get("newsSunmmary2"));
                            tvCommentnum2.setText((String) relatedList.get(position).get("newsCommentNum2") + "跟帖");

                            //设置加载图片时等待的图片和失败的图片

                            ImageOptions options = new ImageOptions.Builder()
                                    .setLoadingDrawableId(R.mipmap.ic_launcher)
                                    .setFailureDrawableId(R.mipmap.broke_sel)
                                    .build();

                            x.image().bind(newsCover2, "http://tr.zzapi.gson.cn/" +
                                    (String) relatedList.get(position).get("newsCover2"), options);

                            if (relatedList.get(position).get("newsCover2").equals("")) {
                                newsCover2.setVisibility(View.GONE);
                            } else {
                                newsCover2.setVisibility(View.VISIBLE);
                            }

                            return root;
                        } else {
                            tvRelated.setVisibility(View.VISIBLE);
                            return null;
                        }
                    }
                }

                seeNewsRelated.setAdapter(new SeeNewsRelatedAdapter());
                setTotalHeightofListView(seeNewsRelated);
                /**
                 * 相关新闻的点击事件
                 */
                seeNewsRelated.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(SeeNewsActivity.this, SeeNewsActivity.class);
                        intent.putExtra("newsId", (CharSequence) relatedList.get(position).get("newsId"));
                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {
                //Toast.makeText(SeeNewsActivity.this, "完成了", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * MenuItem的监听
     *
     * @param clickedView
     * @param position
     */
    @Override
    public void onMenuItemClick(View clickedView, int position) {
        switch (position) {
            case 1:
                if (judgeCollection()) {
                    RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/news/favorites?id=" + newsId);
                    params.addQueryStringParameter("id", newsId);
                    x.http().get(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            Toast.makeText(SeeNewsActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();
                            Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.shoucang);
                            getMenuObjects().get(1).setBitmap(b);
                        }

                        @Override
                        public void onError(Throwable throwable, boolean b) {

                        }

                        @Override
                        public void onCancelled(CancelledException e) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                } else {
                    RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/news/favorites?id=" + newsId);
                    params.addQueryStringParameter("id", newsId);
                    x.http().get(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            Toast.makeText(SeeNewsActivity.this, "已收藏", Toast.LENGTH_SHORT).show();
                            Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.shoucang_sel);
                            getMenuObjects().get(1).setBitmap(b);
                        }

                        @Override
                        public void onError(Throwable throwable, boolean b) {

                        }

                        @Override
                        public void onCancelled(CancelledException e) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                }
        }
    }

    /**
     * 在WebView中打开链接，而不是在浏览器中打开链接
     * 弹出进度条对话框等待
     */
    class MyWebViewClient extends WebViewClient {
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        /**
         * 当打开链接时自动调用
         *
         * @param view
         * @param url  链接地址
         * @return
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view,
                                                String url) {
            view.loadUrl(url);//本WebView打开链接地址
            return true;//本链接由WebView打开了，无需其他应用来打开
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            mProgressDialog = new ProgressDialog(SeeNewsActivity.this);
            mProgressDialog.setTitle("正在加载");
            mProgressDialog.setMessage("正在加载，请等待……");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressDialog.dismiss();
        }
    }

    /**
     * 查看所有评论
     */
    private class SeeMoreComment implements View.OnClickListener {
        private final String newsId;

        public SeeMoreComment(String newsId) {
            this.newsId = newsId;
        }

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SeeNewsActivity.this, CommentActivity.class);
            intent.putExtra("newsId", newsId);
            startActivity(intent);
        }
    }

    /**
     * 动态的设置相关新闻的高度
     */
    public void setTotalHeightofListView(ListView listView) {
        ListAdapter mAdapter = listView.getAdapter();
        if (mAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < mAdapter.getCount(); i++) {
            View mView = mAdapter.getView(i, null, listView);
            mView.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            //mView.measure(0, 0);
            totalHeight += mView.getMeasuredHeight();
            Log.w("HEIGHT" + i, String.valueOf(totalHeight));
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    /**
     * webview页面关闭后视频和声音也随之关闭
     */
    @Override
    protected void onPause() {
        super.onPause();
        //newsWebview.reload();
    }

    /**
     * 添加菜单碎片
     */
    private void initMenuFragment() {
        MenuParams menuParams = new MenuParams();
        menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
        menuParams.setMenuObjects(getMenuObjects());
        menuParams.setClosableOutside(false);
        mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
        //此处决定MenuItem的监听事件
        mMenuDialogFragment.setItemClickListener(this);
    }

    /**
     * 添加菜单
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.context_menu:
                if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
                    mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 菜单中的选项
     *
     * @return
     */
    private List<MenuObject> getMenuObjects() {

        // You can use any [resource, bitmap, drawable, color] as image:
        // item.setResource(...)
        // item.setBitmap(...)
        // item.setDrawable(...)
        // item.setColor(...)
        // You can set image ScaleType:
        // item.setScaleType(ScaleType.FIT_XY)
        // You can use any [resource, drawable, color] as background:
        // item.setBgResource(...)
        // item.setBgDrawable(...)
        // item.setBgColor(...)
        // You can use any [color] as text color:
        // item.setTextColor(...)
        // You can set any [color] as divider color:
        // item.setDividerColor(...)

        List<MenuObject> menuObjects = new ArrayList<>();

        MenuObject close = new MenuObject();
        close.setResource(R.mipmap.menu_close);

        MenuObject collection = new MenuObject("收藏");
        collection.setResource(R.mipmap.shoucang);

        MenuObject good = new MenuObject("点赞");
        good.setResource(R.mipmap.zan_nor);

        MenuObject share = new MenuObject("分享");
        share.setResource(R.mipmap.share002);

        MenuObject night = new MenuObject("夜间");
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.night002);
        night.setBitmap(b);

        /*MenuObject addFr = new MenuObject("Add to friends");
        BitmapDrawable bd = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
        addFr.setDrawable(bd);

        MenuObject addFav = new MenuObject("Add to favorites");
        addFav.setResource(R.drawable.icn_4);

        MenuObject block = new MenuObject("Block user");
        block.setResource(R.drawable.icn_5);*/

        menuObjects.add(close);

        menuObjects.add(collection);
        menuObjects.add(share);
        menuObjects.add(night);
        return menuObjects;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    /**
     * 设置软键盘上的按钮
     */
    /*private void hintKbOne() {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// 得到InputMethodManager的实例
        if (imm.isActive()&&getCurrentFocus()!=null) {
            // 如果关闭
            ivShare.setVisibility(View.GONE);
            rvMoreComment.setVisibility(View.GONE);
            tvSendComment.setVisibility(View.VISIBLE);

        }else {
            //开启
            tvSendComment.setVisibility(View.GONE);
            ivShare.setVisibility(View.VISIBLE);
            rvMoreComment.setVisibility(View.VISIBLE);

        }
    }*/

    /**
     * 物理返回键的监听
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            if (tvSendComment.getVisibility() == View.VISIBLE) {
                sendMyComment.setSelected(false);
                evText = String.valueOf(sendMyComment.getText());
                sendMyComment.setText("");
                sendMyComment.setHint("我来说两句...");
                //Toast.makeText(SeeNewsActivity.this, sendMyComment.getText(), Toast.LENGTH_SHORT).show();

                tvSendComment.setVisibility(View.GONE);
                rvMoreComment.setVisibility(View.VISIBLE);
                ivShare.setVisibility(View.VISIBLE);
                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * edittext监听器
     */
    private class SendMyCommentOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            tvSendComment.setVisibility(View.VISIBLE);
            ivShare.setVisibility(View.GONE);
            rvMoreComment.setVisibility(View.GONE);
            sendMyComment.setText(evText);
        }
    }

    /**
     * 发表评论
     */
    private class SendCommentListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            RequestParams params2 = new RequestParams("http://tr.zzapi.gson.cn/api/comment/comment");
            //evText = String.valueOf(sendMyComment.getText());

            if (evText.length() >= 2) {
                params2.addBodyParameter("newsId", newsId);
                params2.addBodyParameter("content", evText);
                x.http().post(params2, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Toast.makeText(SeeNewsActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                        tvSendComment.setVisibility(View.GONE);
                        ivShare.setVisibility(View.VISIBLE);
                        rvMoreComment.setVisibility(View.VISIBLE);
                        sendMyComment.setText("");
                        sendMyComment.setHint("我来说两句...");
                        View view = getWindow().peekDecorView();
                        InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }

                    @Override
                    public void onError(Throwable throwable, boolean b) {

                    }

                    @Override
                    public void onCancelled(CancelledException e) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            } else {
                Toast.makeText(SeeNewsActivity.this, "内容不得少于两个字", Toast.LENGTH_SHORT).show();
            }


        }
    }

    /**
     * 判断收藏的状态
     */
    private boolean judgeCollection() {
        final List<String> list = new ArrayList<String>();
        RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/user/favorites?page=1&rows=10");
        params.addQueryStringParameter("page", "1");
        params.addBodyParameter("rows", "10");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                //Toast.makeText(SeeNewsActivity.this,s, Toast.LENGTH_SHORT).show();
                JSONObject jsonobject = JSON.parseObject(s);
                JSONArray datas = jsonobject.getJSONArray("data");
                for (int i = 0; i < datas.size(); i++) {
                    JSONObject data = datas.getJSONObject(i);
                    Integer id = data.getInteger("id");
                    //Toast.makeText(SeeNewsActivity.this, id, Toast.LENGTH_SHORT).show();
                    list.add(String.valueOf(id));
                }
                if (list.contains(newsId)) {
                    bool = 1;
                } else {
                    bool = 0;
                }
                ;
            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
        if (bool == 1) {
            return true;
        } else
            return false;
    }

    /**
     * 显示分享
     */
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题：微信、QQ（新浪微博不需要标题）
        oks.setTitle(newsTitle);  //最多30个字符

        // text是分享文本：所有平台都需要这个字段
        //oks.setText("我是分享文本，啦啦啦~http://uestcbmi.com/");  //最多40个字符
        oks.setText(newsSunmmary);

        // imagePath是图片的本地路径：除Linked-In以外的平台都支持此参数
        //oks.setImagePath(Environment.getExternalStorageDirectory() + "/meinv.jpg");//确保SDcard下面存在此张图片

        //网络图片的url：所有平台
        oks.setImageUrl("http://tr.zzapi.gson.cn/" + newsCover);//网络图片rul

        // url：仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");   //网友点进链接后，可以看到分享的详情

        // Url：仅在QQ空间使用
        oks.setTitleUrl(fromUrl);  //网友点进链接后，可以看到分享的详情


        // 启动分享GUI
        oks.show(this);
    }

    private class NewsCommentAdapter extends BaseAdapter {
        private final JSONArray comments;

        public NewsCommentAdapter(JSONArray comments) {
            this.comments = comments;
        }

        @Override
        public int getCount() {
            if (commentList.size() < 3) {
                return commentList.size();
            }
            return 3;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (comments != null) {
                tvCommentNone.setVisibility(View.INVISIBLE);
                View root = getLayoutInflater().inflate(R.layout.see_news_comment_listview_item, null);
                //评论人头像
                newsCommentAvatar = (ImageView) root.findViewById(R.id.news_comment_avatar);
                ImageOptions avatarOptions = new ImageOptions.Builder()
                        .setCircular(true)
                        .setLoadingDrawableId(R.mipmap.ic_launcher)
                        .setFailureDrawableId(R.mipmap.default_avatar)
                        .build();
                x.image().bind(newsCommentAvatar,
                        "http://tr.zzapi.gson.cn/" + commentList.get(position).get(newsCommentAvatar),
                        avatarOptions);

                newsCommentNickname = (TextView) root.findViewById(R.id.news_comment_username);
                newsCommentNickname.setText(commentList.get(position).get("commentNickName"));

                newsCommentSex = (ImageView) root.findViewById(R.id.news_comment_sex);
                if (commentList.get(position).get("commentGenter").equals("BOY")) {
                    newsCommentSex.setImageResource(R.mipmap.boy);
                } else if (commentList.get(position).get("commentGenter").equals("GIRL")) {
                    newsCommentSex.setImageResource(R.mipmap.girl);
                }
                //Toast.makeText(SeeNewsActivity.this,commentList.get(position).get("commentGenter") , Toast.LENGTH_SHORT).show();

                good = (ImageView) root.findViewById(R.id.news_comment_good);

                newsCommentGoodNumber = (TextView) root.findViewById(R.id.news_comment_good_number);
                //newsCommentGoodNumber.setText(commentGood);

                bad = (ImageView) findViewById(R.id.news_comment_bad);

                newsCommentBadNumber = (TextView) root.findViewById(R.id.news_comment_bad_number);
                //newsCommentBadNumber.setText(commentBad);

                newsCommentTime = (TextView) root.findViewById(R.id.news_comment_time);
                newsCommentTime.setText(commentList.get(position).get("commentDateline"));

                newsCommentContent = (TextView) root.findViewById(R.id.news_comment_content);
                newsCommentContent.setText(commentList.get(position).get("commentContent"));

                newsCommentArea = (TextView) root.findViewById(R.id.news_comment_area);
                newsCommentArea.setText(commentList.get(position).get("area"));

                return root;
            } else {
                tvCommentNone.setVisibility(View.VISIBLE);
                //seeMoreComment.setVisibility(View.INVISIBLE);
                return null;
            }
        }
    }

    //赞方法
    public void good(final String goodId) {
        LinearLayout goodView = (LinearLayout) findViewById(R.id.good_linear);
        goodView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点赞
                RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/news/goodOrBad?id=" + goodId + "&type=GOOD");
                x.http().get(params, new Callback.CommonCallback<String>() {

                    @Override
                    public void onSuccess(String s) {
                        JSONObject good_json = JSON.parseObject(s);
                        final String sss = good_json.getString("message");
                        Toast.makeText(SeeNewsActivity.this, sss, Toast.LENGTH_SHORT).show();
                        //获取爆料列表设置赞的数量
                        RequestParams params = new RequestParams(
                                "http://tr.zzapi.gson.cn/api/news/detail?id=" + newsId + "");
                        x.http().get(params, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                JSONObject jsonobject = JSON.parseObject(s);
                                JSONObject data = JSON.parseObject(jsonobject.getString("data"));
                                JSONObject news = JSON.parseObject(data.getString("news"));

                                String newsGood = news.getString("good");
                                String newsBad = news.getString("bad");
                                tvGood.setText(newsGood);//设置赞
                                if (sss.equals("赞成功")) {
                                    ImageView good_img = (ImageView) findViewById(R.id.good_img);
                                    good_img.setImageResource(R.mipmap.ysw_good2);
                                } else {
                                    ImageView good_img = (ImageView) findViewById(R.id.good_img);
                                    good_img.setImageResource(R.mipmap.ysw_good1);
                                }


                            }

                            @Override
                            public void onError(Throwable throwable, boolean b) {
                            }

                            @Override
                            public void onCancelled(CancelledException e) {
                            }

                            @Override
                            public void onFinished() {
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable throwable, boolean b) {

                    }

                    @Override
                    public void onCancelled(CancelledException e) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        });
    }

    public void bad(final String badId) {
        LinearLayout badView = (LinearLayout) findViewById(R.id.bad_linear);
        badView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //踩
                RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/news/goodOrBad?id=" + badId + "&type=BAD");
                x.http().get(params, new Callback.CommonCallback<String>() {

                    @Override
                    public void onSuccess(String s) {
                        JSONObject bad_json = JSON.parseObject(s);
                        final String sss = bad_json.getString("message");
                        Toast.makeText(SeeNewsActivity.this, sss, Toast.LENGTH_SHORT).show();
                        //获取爆料列表设置踩的数量
                        RequestParams params = new RequestParams(
                                "http://tr.zzapi.gson.cn/api/news/detail?id=" + newsId + "");
                        x.http().get(params, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                JSONObject jsonobject = JSON.parseObject(s);
                                JSONObject data = JSON.parseObject(jsonobject.getString("data"));
                                JSONObject news = JSON.parseObject(data.getString("news"));

                                String newsGood = news.getString("good");
                                String newsBad = news.getString("bad");
                                tvBad.setText(newsBad);//设置踩
                                if (sss.equals("踩成功")) {
                                    ImageView bad_img = (ImageView) findViewById(R.id.bad_img);
                                    bad_img.setImageResource(R.mipmap.ysw_bad2);
                                } else {
                                    ImageView bad_img = (ImageView) findViewById(R.id.bad_img);
                                    bad_img.setImageResource(R.mipmap.ysw_bad1);
                                }

                            }

                            @Override
                            public void onError(Throwable throwable, boolean b) {
                            }

                            @Override
                            public void onCancelled(CancelledException e) {
                            }

                            @Override
                            public void onFinished() {
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable throwable, boolean b) {

                    }

                    @Override
                    public void onCancelled(CancelledException e) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        });
    }

}
